﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NetMicro.Core.ApiFunction;
using NetMicro.Core.Claims;
using NetMicro.Core.Encryptions;
using NetMicro.Core.Extensions;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace NetMicro.Webs.Auth.Attribute
{
    /// <summary>
    /// token验证解析
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
    public class TokenAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter
    {
        /// <summary>
        /// 解析token
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            //排除匿名访问
            if (context.ActionDescriptor.EndpointMetadata.Any(m => m.GetType() == typeof(AllowAnonymousAttribute)))
                return;
            if (!context.HttpContext.User.HasClaim(c => c.Type == ClaimsName.Context))
            {
                context.Result = new OkObjectResult(ServiceResult.Faild(401, "未授权"));
                return;
            }
            var datakey = context.HttpContext.User.FindFirstValue(ClaimsName.Context);
            if (string.IsNullOrWhiteSpace(datakey))
            {
                context.Result = new OkObjectResult(ServiceResult.Faild(401, "未授权"));
                return;
            }
            var context_type = context.HttpContext.User.FindFirstValue(ClaimsName.ContextType).ToBool();
            var data = DESCEncryption.Decrypt(datakey, Penetrates.ContextEncryptionKey);
            context.HttpContext.Request.Headers.Add("isAdminApi", context_type.ToString());
            if (context_type)
                context.HttpContext.Request.Headers.Add("adminContext", data);
            else
                context.HttpContext.Request.Headers.Add("webContext", data);
        }
    }
}
